﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Threading;
using System.Windows.Forms;
using Infragistics.Win.UltraWinExplorerBar;
using Litografia.BusinessComponents;
using Litografia.UI.Mantenimientos;
using Litografia.UI.Procesos;
using Infragistics.Win.UltraWinToolbars;
using Litografia.UI.Reports;
using Microsoft.Practices.EnterpriseLibrary.Security;
using Nortec.Security;
using Litografia.UI.Seguridad;
using Microsoft.Reporting.WinForms;
using System.Collections;
using System.Configuration;
using System.Text.RegularExpressions;

namespace Litografia.UI
{
    public partial class PrincipalForm : Form
    {
        public PrincipalForm()
        {
            InitializeComponent();
        }

        #region Declarations
        const string ConnectionStringPattern = @"Data Source=(?<sqlServerName>.+);Initial Catalog=(?<databaseName>\w+);";
        static readonly Regex connectionStringRegex = new Regex(ConnectionStringPattern, RegexOptions.IgnoreCase);

        private enum ReportType
        {
            Resumido,
            Detallado
        }
        private const string OTDetalleReport = "Litografia.UI.Reports.OTDetalle.rdlc";
        private const string OTResumenReport = "Litografia.UI.Reports.OTResumen.rdlc";

        private readonly Hashtable mantForms = new Hashtable();
        #endregion

        #region Event Handlers
        private void toolbarManager_ToolClick(object sender, ToolClickEventArgs e)
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                switch (e.Tool.Key)
                {
                    case "tabbedMdiTool":
                        tabbedMdiManager.Enabled = !((StateButtonTool)e.Tool).Checked;
                        break;
                    case "Registro de OT":
                        ShowScreen(new HojaRegistroForm());
                        break;
                    case "Registro de Cotizacion":
                        ShowScreen(new RegistroOTForm());
                        break;
                    case "CloseAllWindowsTool":
                        CloseAllWindows();
                        break;
                    case "LeftMenuTool":
                        dockManager.Visible = ((StateButtonTool)e.Tool).Checked;
                        break;
                    case "Cerrar Aplicacion":
                        Close();
                        break;
                    case "Cerrar Sesion":
                        LogOff();
                        Login();
                        break;
                    case "ReporteHojaRegistroDetallado":
                        ShowScreen(new BusquedaOTForm());
                        break;
                    case "ReporteHojaRegistroResumen":
                        PrintWOReport(ReportType.Resumido);
                        break;
                    case "Reporte de horas laboradas":
                        ShowScreen(new HorasPorOperarioForm());
                        break;
                    case "About":
                        new AboutForm().ShowDialog();
                        break;
                    case "DataSource":
                        break;
                    default:
                        ShowMantForm(e.Tool.Key);
                        break;
                }
            }
            finally
            {
                Cursor = Cursors.Arrow;
            }
            
        }
        private void explorerBar_ItemClick(object sender, ItemEventArgs e)
        {
            switch (e.Item.Key)
            {
                case "Registro de Cotizacion":
                    ShowScreen(new RegistroOTForm());
                    break;

                case "Registro de OT":
                    ShowScreen(new HojaRegistroForm());
                    break;

                case "Requisicion":
                    ShowScreen(new RequisicionForm());
                    break;

                case "ReporteHojaRegistroDetallado":
                    ShowScreen(new BusquedaOTForm());
                    break;

                case "ReporteHojaRegistroResumen":
                    PrintWOReport(ReportType.Resumido);
                    //ShowScreen(new BusquedaOTForm("Resumen"));
                    break;

                case "Reporte de horas laboradas":
                    ShowScreen(new HorasPorOperarioForm());
                    break;

                default:
                    ShowMantForm(e.Item.Key);
                    break;
            }
        }
        private void toolbarManager_AfterRibbonTabSelected(object sender, RibbonTabEventArgs e)
        {
            if (e.Tab != null)
                SetExporerGroup(e.Tab.Key);
        }
        private void explorarBar_GroupClick(object sender, GroupEventArgs e)
        {
            var selectedTab = toolbarManager.Ribbon.Tabs[e.Group.Key];
            if (selectedTab != null)
                toolbarManager.Ribbon.SelectedTab = selectedTab;
        }
        private void PrincipalForm_Load(object sender, EventArgs e)
        {
            var connectionString = ConfigurationManager.ConnectionStrings["Operacion"].ConnectionString;
            var groups = ParseConnectionString(connectionString);
            toolbarManager.Tools["DataSource"].SharedProps.Caption = "[Conectado a " + groups[2].Value + " en servidor " + groups[1].Value + "]";
            ConfigureCulture();
            LogOff();
            Login();
        }
        private void Login()
        {
            var form = new LoginForm();
            var result = form.ShowDialog();
            if (result == DialogResult.Cancel)
                Application.Exit();
            else
            {
                LoadMenuPermissions();
                LoadLeftNavPermissions();
            }
        }
        #endregion

        #region Methods: Public

        #endregion

        #region Methods: Non-Public
        
        static GroupCollection ParseConnectionString(string inputString)
        {
            Match match = connectionStringRegex.Match(inputString);
            return match.Groups;
        }

        private void ShowMantForm(string key)
        {
            object f = mantForms[key];
            bool tabFound = false;


            if (f == null)
                CreateMantForm(key);
            else
            {
                if (tabbedMdiManager.TabGroups.Count > 0)
                {
                    var form = (Form)f;
                    for (int i = 0; i < tabbedMdiManager.TabGroups[0].Tabs.Count; i++)
                    {
                        if (form.Equals(tabbedMdiManager.TabGroups[0].Tabs[i].Form))
                        {
                            tabbedMdiManager.TabGroups[0].Tabs[i].Activate();
                            tabFound = true;
                        }
                    }
                }

                if (!tabFound)
                    CreateMantForm(key);
            }
        }

        private void CreateMantForm(string key)
        {
            var form = new Form();
            switch (key)
            {
                case "Usuarios":
                    form = new UsuariosForm();
                    break;
                case "Roles":
                    form = new RolesForm();
                    break;
                case "Puestos":
                    form = new MantPuestosForm();
                    break;
                case "Operarios":
                    form = new MantOperariosForm();
                    break;
                case "Maquinas":
                    form = new MantMaquinasForm();
                    break;
                case "Gastos":
                    form = new MantGastosForm();
                    break;
                case "Bodegas":
                    form = new MantParametrosBodegaForm();
                    break;
            }
            if (mantForms.ContainsKey(key))
                mantForms.Remove(key);
            mantForms.Add(key, form);
            ShowScreen(form);
        }

        private void PrintWOReport(ReportType reportType)
        {
            var paramForm = new ReporteOTParametrosForm();
            if (paramForm.ShowDialog() == DialogResult.OK)
            {
                DataSet data;
                var parameters = new List<ReportParameter>
                                     {
                                         new ReportParameter("EmpresaNombre", NortecMembership.CompanyName),
                                         new ReportParameter("NumeroOrden", paramForm.WorkOrder),
                                         new ReportParameter("Estado", paramForm.StatusName)
                                     };
                if (paramForm.BeginDate.HasValue)
                    parameters.Add(new ReportParameter("FechaInicial", paramForm.BeginDate.Value.ToString("dd/MM/yyyy")));
                else
                    parameters.Add(new ReportParameter("FechaInicial", ""));

                if (paramForm.EndDate.HasValue)
                    parameters.Add(new ReportParameter("FechaFinal", paramForm.EndDate.Value.ToString("dd/MM/yyyy")));
                else
                    parameters.Add(new ReportParameter("FechaFinal", ""));

                if (reportType == ReportType.Detallado)
                {
                    data = BCOrdenTrabajo.RegistroOTDetalleReporteGet(paramForm.WorkOrder, paramForm.Status, paramForm.BeginDate, paramForm.EndDate);
                    PrintReport(OTDetalleReport, "Reporte OT Detallado", data, parameters);
                }
                else if (reportType == ReportType.Resumido)
                {
                    data = BCOrdenTrabajo.RegistroOTResumenReporteGet(paramForm.WorkOrder, paramForm.Status, paramForm.BeginDate, paramForm.EndDate);
                    PrintReport(OTResumenReport, "Reporte OT Resumido", data, parameters);
                }
            }
        }

        private void PrintReport(string name, string title, DataSet data, IEnumerable<ReportParameter> parameters)
        {
            var report = new ReportViewerForm { ReportTitle = title };
            report.BuildReport(data, name, parameters);
            ShowScreen(report);
        }

        private void CloseAllWindows()
        {
            foreach (Form form in MdiChildren)
                form.Close();
        }

        private void SetExporerGroup(string groupKey)
        {
            var dockPane = (Infragistics.Win.UltraWinDock.DockableControlPane)dockManager.DockAreas[0].Panes[0];
            var explorerBar = (UltraExplorerBar)dockPane.Control;
            UltraExplorerBarGroup group = explorerBar.Groups[groupKey];
            if (group != null)
                group.Selected = true;
        }

        private void ShowScreen(Form form)
        {
            form.MdiParent = this;
            ActivateMdiChild(form);
            form.Show();
        }

        private static void ConfigureCulture()
        {
            var currentCulture = new CultureInfo("es-CR")
                                     {
                                         DateTimeFormat = { ShortDatePattern = "dd/MM/yyyy" },
                                         NumberFormat =
                                             {
                                                 CurrencyDecimalSeparator = ".",
                                                 NumberDecimalSeparator = ".",
                                                 CurrencyGroupSeparator = ",",
                                                 NumberGroupSeparator = ","
                                             }
                                     };
            Thread.CurrentThread.CurrentCulture = currentCulture;
        }

        private void LogOff()
        {
            var dockPane = (Infragistics.Win.UltraWinDock.DockableControlPane)dockManager.DockAreas[0].Panes[0];
            var explorerBar = (UltraExplorerBar)dockPane.Control;

            CloseAllWindows();

            foreach (RibbonTab tab in toolbarManager.Ribbon.Tabs)
                tab.Visible = false;

            foreach (UltraExplorerBarGroup group in explorerBar.Groups)
            {
                foreach (UltraExplorerBarItem item in group.Items)
                    item.Visible = false;

                group.Visible = false;
            }


        }

        private void LoadMenuPermissions()
        {
            var authProvider = AuthorizationFactory.GetAuthorizationProvider();
            foreach (RibbonTab tab in toolbarManager.Ribbon.Tabs)
            {
                var visibleTab = false;
                foreach (RibbonGroup group in tab.Groups)
                    foreach (var tool in group.Tools)
                    {
                        if (authProvider.Authorize(NortecMembership.Principal, tool.Key))
                        {
                            tool.SharedProps.Visible = true;
                            visibleTab = true;
                        }
                        else tool.SharedProps.Visible = false;

                        if (tool is PopupMenuTool)
                        {
                            var parentTool = (PopupMenuTool)tool;
                            foreach (var childTool in parentTool.Tools)
                            {
                                if (authProvider.Authorize(NortecMembership.Principal, childTool.Key))
                                {
                                    childTool.SharedProps.Visible = true;
                                    visibleTab = true;
                                }
                                else childTool.SharedProps.Visible = false;
                            }
                        }
                    }
                tab.Visible = (authProvider.Authorize(NortecMembership.Principal, tab.Key) && visibleTab);
            }
        }

        private void LoadLeftNavPermissions()
        {
            var authProvider = AuthorizationFactory.GetAuthorizationProvider();
            var dockPane = (Infragistics.Win.UltraWinDock.DockableControlPane)dockManager.DockAreas[0].Panes[0];
            var explorerBar = (UltraExplorerBar)dockPane.Control;
            foreach (var group in explorerBar.Groups)
            {
                var visibleGroup = false;
                foreach (var item in group.Items)
                    if (authProvider.Authorize(NortecMembership.Principal, item.Key))
                    {
                        item.Visible = true;
                        visibleGroup = true;
                    }
                    else
                        item.Visible = false;

                group.Visible = visibleGroup;
            }
        }

        #endregion

    }
}
